package com.qxglxt.qxgl.service;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import com.qxglxt.qxgl.dao.IUsersDao;
import com.qxglxt.qxgl.dto.UsersDTO;
import com.qxglxt.qxgl.model.Users;


import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Expression;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

@Service
public class UsersServiceImpl implements IUsersService {

    protected static final Root<Users> Date = null;
	@Resource
    private IUsersDao usersDao;

    @Override
    public Page<Users> findPage(UsersDTO dto) {
        Sort sort = Sort.by(Sort.Order.asc("id"));
        Pageable page = PageRequest.of((dto.getPage() - 1) * dto.getLimit(), dto.getLimit(), sort);
        return usersDao.findAll(getWhereClause(dto), page);
    }

    private Specification<Users> getWhereClause(UsersDTO dto) {
        return new Specification<Users>() {

            /**
             *
             */
            private static final long serialVersionUID = 1L;

            @Override
            public Predicate toPredicate(Root<Users> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
               Predicate predicate = criteriaBuilder.conjunction();
               List<Expression<Boolean>> exlList = predicate.getExpressions();
               if (dto.getLoginName()!=null &&"".equals(dto.getLoginName())) {
                   exlList.add(criteriaBuilder.equal(root.<String>get("loginName"),"%"+dto.getLoginName()+"%"));                   
               } 
               if (dto.getStartcreateTime()!=null) {
                   exlList.add(criteriaBuilder.greaterThanOrEqualTo(root.<Date>get("createTime"),dto.getStartcreateTime()));
               }
              if (dto.getEndLastcreateTime()!=null) {
                  exlList.add(criteriaBuilder.lessThanOrEqualTo(root.<Date>get("createTime"), dto.getEndLastcreateTime()));
              }
              if (dto.getIsLockout()!=null &&"".equals(dto.getIsLockout())) {
                  exlList.add(criteriaBuilder.equal(root.<String>get("isLockout"),dto.getIsLockout()));
              }
               return predicate;
            }

        };
    }

    @Override
    public Users saveUsers(Users u) {    
        return usersDao.save(u);
    }

    @Override
    public void del(Integer id) {
       usersDao.deleteById(id);

    }

}